//
//  TTFavoriteStationsViewController.m
//  TrainTrack
//
//  Created by Jonathan Bunde-Pedersen on 06/10/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "TTFavoriteStationsViewController.h"
#import "TrainTrackAppDelegate.h"

@implementation TTFavoriteStationsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
		
		TrainTrackAppDelegate *appController = (TrainTrackAppDelegate *)[[UIApplication sharedApplication] delegate];
		
		self.stations = [appController.model fetchFavouriteStations];
		editBarButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStylePlain target:self action:@selector(editClicked)];
		[self.navigationItem setLeftBarButtonItem:editBarButton];		
		
	}
	return self;
}


- (void) editClicked {
	[self setEditing:![self isEditing] animated:YES];
	if([self isEditing]) {
		[editBarButton setTitle:@"Done"];
		[editBarButton setStyle:UIBarButtonItemStyleDone];
	}
	else {
		[editBarButton setTitle:@"Edit"];
		[editBarButton setStyle:UIBarButtonItemStylePlain];
	}
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
	if (editingStyle == UITableViewCellEditingStyleDelete) {
		// delete from db - assume we're on main thread
		TrainTrackAppDelegate *appController = (TrainTrackAppDelegate *)[[UIApplication sharedApplication] delegate];
		[appController deleteFavStation:[self.stations objectAtIndex:indexPath.row]];
		// delete from table
		[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
		
		self.stations = [appController.model fetchFavouriteStations];
		[self.tableView reloadData];
	}
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}

- (void)viewWillAppear:(BOOL)animated {
	TrainTrackAppDelegate *appController = (TrainTrackAppDelegate *)[[UIApplication sharedApplication] delegate];
	self.stations = [appController.model fetchFavouriteStations];
	
	[self.tableView reloadData];
	
	NSIndexPath *selection = [self.tableView indexPathForSelectedRow];
	if (selection) {
		[self.tableView deselectRowAtIndexPath:selection animated:YES];	
	}
}

@end
